<template>
  <div class="field-container">
    <el-dialog
      :visible.sync="visible"
      :before-close="handleCloseDialog"
      :title="dialogFormTitle">
      <el-steps :active="stepActive" finish-status="success" align-center>
        <el-step title="基本信息"/>
        <el-step title="活动介绍"/>
        <el-step title="组织单位"/>
        <el-step title="分类投放"/>
      </el-steps>
      <el-form
        ref="dataForm"
        :model.sync="dialogModel"
        label-position="left"
        label-width="120px"
        size="mini"
        class="dialogModel"
      >
        <div v-show="stepActive == 0" class="step step-1">
          <el-row :gutter="40">
            <el-col :span="12" :xs="24">
              <el-form-item
                :rules="{ required: true, message: '名称不能为空', trigger: 'blur' }"
                label="名称"
                prop="AcName">
                <el-input v-model="dialogModel.AcName"/>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '地点不能为空', trigger: 'blur' }"
                label="地点"
                prop="AcSite">
                <el-input v-model="dialogModel.AcSite"/>
              </el-form-item>
              <el-form-item
                ref="AcBegin"
                :rules="{ required: true, message: '请选择开始和结束时间', trigger: ['blur', 'change'] }"
                label="活动时间"
                prop="AcRangeTime">
                <el-date-picker
                  v-model="dialogModel.AcRangeTime"
                  style="width:100%"
                  type="datetimerange"
                  range-separator="~"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"/>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '请选择活动类别', trigger: ['blur', 'change'] }"
                label="活动类别"
                prop="AcType">
                <el-select v-model="dialogModel.AcType" placeholder="请选择">
                  <el-option
                    v-for="item in config.activityKindOptions"
                    :value="item.value"
                    :label="item.label"
                    :key="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '活动版块不能为空', trigger: ['blur', 'change'] }"
                label="活动版块"
                prop="AcClassify">
                <el-select v-model="dialogModel.AcClassify" placeholder="请选择">
                  <el-option
                    v-for="item in config.activityClassOptions"
                    :value="item.value"
                    :label="item.label"
                    :key="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item
                :rules="{ required: true, message: '请选择活动验证方式', trigger: ['blur', 'change'] }"
                label="活动验证方式"
                prop="AcVerify">
                <el-select
                  v-model="dialogModel.AcVerify"
                  placeholder="选择验证方式"
                  clearable
                  class="filter-item"
                >
                  <el-option
                    v-for="item in config.activityVerificationMethod"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '请选择活动所在学年', trigger: ['blur', 'change'] }"
                label="活动所在学年"
                prop="AcYear">
                <el-select
                  v-model="dialogModel.AcYear"
                  placeholder="选择学年"
                  clearable
                  class="filter-item"
                >
                  <el-option
                    v-for="item in config.activityYearOptions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '请选择活动所在学期', trigger: 'change' }"
                label="活动所在学期"
                prop="AcTerm">
                <el-radio-group v-model="dialogModel.AcTerm">
                  <el-radio label="1">第一学期</el-radio>
                  <el-radio label="2">第二学期</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '学分不能为空', trigger: ['blur', 'change'] }"
                label="学分"
                prop="AcCredit">
                <el-input-number
                  v-model="dialogModel.AcCredit"
                  :min="0.01"
                  :step="0.05"
                  :precision="2"
                />
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '人数上限不能为空', trigger: ['blur', 'change'] }"
                label="活动人数上限"
                prop="AcNumber">
                <el-input-number v-model="dialogModel.AcNumber" :min="1" :step="10" :precision="0"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-show="stepActive == 1" class="step step-2">
          <tinymce :height="280" v-model="dialogModel.AcIntroduce" menubar/>
        </div>
        <div v-show="stepActive == 2" class="step step-3">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                :rules="{ required: true, message: '主办单位不能为空', trigger: 'blur' }"
                label="主办单位"
                prop="AcHost">
                <el-input v-model="dialogModel.AcHost"/>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '承办单位不能为空', trigger: 'blur' }"
                label="承办单位"
                prop="AcOrganizer">
                <el-input v-model="dialogModel.AcOrganizer"/>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '指导老师不能为空', trigger: 'blur' }"
                label="指导老师"
                prop="AcTeacher">
                <el-input v-model="dialogModel.AcTeacher"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :rules="{ required: true, message: '活动负责人不能为空', trigger: 'blur' }"
                label="活动负责人"
                prop="AcLeader">
                <el-input v-model="dialogModel.AcLeader"/>
              </el-form-item>
              <el-form-item
                :rules="{ required: true, message: '负责人电话不能为空', trigger: 'blur' }"
                label="负责人电话"
                prop="AcPhone">
                <el-input v-model="dialogModel.AcPhone"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-show="stepActive == 3" class="step step-4">
          <el-row :gutter="20">
            <!--<el-col :span="12">
              <el-form-item
                :rules="{ required: true, message: '投放系部不能为空', trigger: ['blur'] }"
                label="投放系部"
                prop="AcRangeDepa">
                <el-select v-model="dialogModel.AcRangeDepa" multiple placeholder="请选择">
                  <el-option
                    v-for="item in config.departmentOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :rules="{ required: true, message: '投放年级不能为空', trigger: ['blur'] }"
                label="投放年级"
                prop="AcRangeGrade">
                <el-select v-model="dialogModel.AcRangeGrade" multiple placeholder="请选择">
                  <el-option
                    v-for="item in config.rangeGeadeOptions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>-->
            <el-col :span="11" :offset="1">
              <el-form-item
                :rules="{ required: true, validator: validatePass }"
                label="投放班级范围"
                prop="AcRangeClass">
                <div v-loading="classLoading" style="min-height: 150px;max-height: 270px;overflow-y: auto">
                  <el-tree ref="classTree" :data="classData" :default-checked-keys="checkedClass" node-key="id" accordion show-checkbox highlight-current @check="getActivityRange"/>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :rules="{ required: true, message: '投放性别不能为空', trigger: ['blur', 'change'] }"
                label="投放性别"
                prop="AcRangeSex">
                <el-select v-model="dialogModel.AcRangeSex" placeholder="请选择">
                  <el-option
                    v-for="item in config.rangeSexOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="stepActive != 0" @click="handleStepPre">上一步</el-button>
        <el-button v-show="stepActive != 3" @click="handleStepNext">下一步</el-button>
        <el-button v-show="stepActive == 3" :loading="submitLoading" type="primary" @click="submitActivity">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import config from '@/utils/config.js'
import { formatClassTree } from '@/utils/index.js'
import Tinymce from '@/components/Tinymce'
import { createActivity, updateActivity, getClassData } from '@/api/activity'
import { Message } from 'element-ui'

export default {
  name: 'FieldDialog',
  components: { Tinymce },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    dialogModel: {
      type: Object,
      required: true
    },
    mode: {
      type: String,
      required: true
    }
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.dialogModel.AcRangeClass === '') {
        callback(new Error('请选择投放班级范围'))
      } else {
        callback()
      }
    }
    return {
      config,
      stepActive: 0,
      dialogFormTitle: null,
      submitLoading: false,
      classLoading: false,
      classData: [],
      checkedClass: [],
      validatePass
    }
  },
  watch: {
    visible: function(value) {
      if (value) {
        this.checkedClass = this.dialogModel.AcRangeClass || []
      }
    }
  },
  created() {
    const transTitle = {
      create: '创建活动',
      edit: '编辑活动'
    }
    this.dialogFormTitle = transTitle[this.mode] || '活动'
  },
  methods: {
    handleStepPre() {
      if (this.stepActive === 0) {
        return false
      }
      this.stepActive--
    },
    handleStepNext() {
      const self = this
      const stepBox = document.querySelector(`.step-${this.stepActive + 1}`)

      const currentBox = stepBox.querySelectorAll('.el-form-item__label')

      for (let i = 0; i < currentBox.length; i++) {
        validateField(currentBox[i])
      }
      // stepBox.querySelectorAll('.el-form-item__label').forEach(validateField)

      // 校验当前页
      function validateField(item) {
        self.$refs.dataForm.validateField(item.getAttribute('for'))
      }

      if (this.stepActive === 2) {
        this.getClassData()
      }

      if (this.stepActive === 1 && (!this.dialogModel.AcIntroduce || !this.dialogModel.AcIntroduce.length)) {
        Message({ showClose: true, type: 'warning', message: '请填写活动介绍' })
      } else {
        // 下一步
        setTimeout(() => {
          if (!stepBox.querySelector('.el-form-item__error')) {
            self.stepActive++
          }
        })
      }
    },
    dateFormat(time) {
      var date = new Date(time)
      var year = date.getFullYear()
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
    },
    validateStep() {

    },
    submitActivity() {
      this.$refs.dataForm.validateField('AcRangeClass')
      this.$refs.dataForm.validate(valid => {
        if (!valid || document.querySelector('.el-form-item__error')) {
          return
        }

        this.submitLoading = true

        const data = {}
        Object.assign(data, this.dialogModel)

        if (data.AcRangeClass instanceof Array) {
          data.AcRangeClass = data.AcRangeClass.join(',')
        }

        data.AcState = 1

        data.AcBegin = data.AcRangeTime[0]
        data.AcEnd = data.AcRangeTime[1]

        delete data.AcRangeTime

        // 计算活动锁定时间 前十分钟锁定
        const beginTimeString = new Date(data.AcBegin).getTime()
        const oneHourAgo = 1000 * 60 * 10
        data.AcLocktime = this.dateFormat(beginTimeString - oneHourAgo)

        const endTimeString = new Date(data.AcEnd).getTime()
        const threeDaysLate = 259200000 // 1000 * 60 * 60 * 24 * 3
        data.AcOvertime = this.dateFormat(endTimeString + threeDaysLate)

        const submitApi = this.mode === 'create' ? createActivity : updateActivity

        const date = new Date(64067421600000) // 4000年
        this.$store.dispatch('UpdateTokenExpires', { date }).catch(() => {}).finally(() => {
          submitApi(data)
            .then(res => {
              if (res.code === 200) {
                const msg = this.mode === 'create' ? '活动创建成功' : '活动修改成功'
                this.initForm()
                this.$parent.$emit('updateList')
                this.$message({ type: 'success', message: msg })
              } else {
                this.$message({ type: 'error', message: res.msg })
              }
            })
            .finally(() => {
              this.submitLoading = false
            })
        })
      })
    },
    handleCloseDialog() {
      this.$confirm('未保存的数据将会丢失，确认离开当前页面吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('change-visible', false)
        this.initForm()
      }).catch(() => { })
    },
    initForm() {
      this.$refs.dataForm.resetFields()
      this.stepActive = 0
    },
    getClassData() {
      this.classLoading = true
      getClassData()
        .then(res => {
          this.classData = formatClassTree(res.data)
        })
        .catch(() => {})
        .finally(() => {
          this.classLoading = false
        })
    },
    getActivityRange() {
      const checkedNode = this.$refs.classTree.getCheckedNodes()
      let res = ''
      checkedNode.forEach(item => {
        if (item.nodeType === 'class') {
          res = res.length ? `${res},${item.id}` : item.id
        }
      })
      this.dialogModel.AcRangeClass = res
      this.$refs.dataForm.validateField('AcRangeClass')
    }
  }
}
</script>

<style scoped>
.step {
  margin-top: 30px;
}
.step-2 label{
  padding: 0;
}
</style>
<style>
  .field-container .el-dialog {
    width: 60%;
    min-width: 720px;
  }
</style>
